package lerry.nape.body;

import flash.display.Shape;
import flash.display.Sprite;
import lerry.nape.factory.BodyFactory;
import lerry.nape.utils.NapeUtils;
import nape.constraint.DistanceJoint;
import nape.constraint.PivotJoint;
import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyList;
import nape.phys.Compound;
import nape.space.Space;


/**
 * ...
 * @author berry
 */
class Rope{
	var ropelen:UInt;
	public var parent:Compound;
	var cells:BodyList;
	var position:Vec2;
	var line:Shape;
	var space:Space;
	public function new(len:UInt,pos:Vec2,space:Space,con:Sprite) {
		this.ropelen = len;
		this.position = pos;
		this.parent = new Compound();
		this.cells = new BodyList();
		this.space = space;
		parent.space = space;
		line = new Shape();
		con.addChild(line);
		for (i in 0...len) {
			var b:Body = BodyFactory.circle(null, 100, i * 10 + 20, 2);
			b.debugDraw = false;
			cells.add(b);
			b.compound = parent;
		}
		for (i in 0...len-1) {
			var j:DistanceJoint;
				j = new DistanceJoint(cells.at(i), cells.at(i + 1), Vec2.get(0, 2), Vec2.get(0, -2),4,4);
				j.compound = parent;
				j.stiff = false;
				//j.ignore = true;
				j.damping = 5;
				j.frequency = 10;
		}
	}
	public function update():Void {
		line.graphics.clear();
		line.graphics.lineStyle(4,0xff0000);
		for (i in 0...ropelen) {
			var pos:Vec2;
			if (i == 0) {
				pos = cells.at(i).position;
				line.graphics.moveTo(pos.x,pos.y);
			}else {
				pos = cells.at(i).position;
				line.graphics.lineTo(pos.x,pos.y);
			}
		}
	}
	public function setStart(body:Body,pos:Vec2):Void {
		var j:PivotJoint = new PivotJoint(body, cells.at(0), pos, Vec2.get(0, 0));
		j.compound = parent;
		j.stiff = true;
	}
	public function setEnd(body:Body,pos:Vec2):Void {
		var j:PivotJoint = new PivotJoint(body, cells.at(ropelen-1), pos, Vec2.get(0, 0));
		j.compound = parent;
		j.stiff = true;
	}
}